package com.tm.utils;

import com.tm.entity.UserEntity;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;

@Component
public class JwtUtils {

    @Value("${token.sign.secretKey}")
    private String secretKey;

    public String createToken(UserEntity userEntity){

//        Map<String, Object> map = new HashMap<>();
//        map.put("name","afgfa");
        JwtBuilder builder = Jwts.builder();
        builder.setId(userEntity.getId() + "")
                //刷新过期时间    过期时间
                .setExpiration(DateUtils.calendarDate(new Date(),1, Calendar.DATE))
                //.setClaims(map)
                //签名类型和秘钥
                .signWith(SignatureAlgorithm.HS256,"MTIzMw==");
        String token = builder.compact();
        return  token;

    }

    public Claims parseToken(String token){

        Claims body = Jwts.parser().setSigningKey(secretKey)
                .parseClaimsJws(token)
                .getBody();
        return body;

    }

    public static void main(String[] args) {

        JwtUtils jwtUtils = new JwtUtils();
        UserEntity userEntity = new UserEntity();
        userEntity.setId(1L);
        userEntity.setPhone("17852895021");
        userEntity.setName("周六");
        System.out.println("===============================");
        System.out.println(jwtUtils.createToken(userEntity));
        System.out.println("===============================");
        Claims claims = jwtUtils.parseToken("eyJhbGciOiJIUzI1NiJ9.eyJuYW1lIjoiYWZnZmEifQ.-WQXTZp6-eIaeNhWisCRIjux3GiVRrOB7ocpHTSYQoQ");
        System.out.println(claims);
    }

 }


